package com.yd.app.service.sys;

import com.yd.app.mapper.MessageMapper;
import com.yd.app.mapper.UserMapper;
import com.yd.app.service.common.BaseService;
import com.yd.app.service.mobile.messageService.MMessageService;
import com.yd.app.service.ruanwei.interfacej.SmsClientSend;
import com.yd.app.util.BusinessException;
import com.yd.app.util.LoginInfoException;
import com.yd.app.util.SmsModelUtil;
import com.yd.domain.business.Message;
import com.yd.domain.commom.PageModel;
import com.yd.domain.searchParam.MessageReturnParam;
import com.yd.domain.searchParam.UserSearchParam;
import com.yd.domain.sys.DicEnum;
import com.yd.domain.sys.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;


@Service
public class UserService extends BaseService{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Value("${sms.url}")
    private String sms_url;
    @Value("${sms.ID}")
    private String sms_ID;
    @Value("${sms.account}")
    private String sms_account;
    @Value("${sms.psw}")
    private String sms_psw;
    @Autowired
    private MMessageService messageService;

    public User login(String userName, String password) throws Exception {
        User userInfo = userMapper.getUserInfoByUserName(userName);

        if (userInfo != null) {
           boolean flag=false;

            //获取权限code集合
            List<String>listCode=userMapper.getUserPermCode(userInfo.getId());
            if(listCode!=null){
                if(userInfo.getCheckStatus().equals(DicEnum.CHECK.CHECK_NO_PASS)){
                    throw new BusinessException(500,"审核未通过");
                }else if(userInfo.getCheckStatus().equals(DicEnum.CHECK.UN_CHECK)){
                    throw new BusinessException(500,"尚未审核");
                }else{
                    System.out.println("paw=="+passwordEncoding(password, userInfo.getId()));
                    User user = userMapper.getUserById(userInfo.getId());
                    if (user == null) {
                        throw new LoginInfoException(userName);
                    }else{
                        user.setPermCodeList(listCode);
                    }
                    // 密码验证
                    if (passwordEncoding(password, userInfo.getId()).equals(user.getPassword())){
                        return user;
                    } else {
                        throw new LoginInfoException(userName);
                    }
                }
            }else{
                throw new BusinessException(500,"权限不够");
            }

        } else {
            throw new LoginInfoException(userName);
        }
    }

    public User loginDo(String userName,String password) throws BusinessException {
        User userInfo = userMapper.getUserInfoByUserName(userName);

        if (userInfo != null) {
            System.out.println("paw=="+passwordEncoding(password, userInfo.getId()));
            // 密码验证
            if (passwordEncoding(password, userInfo.getId()).equals(userInfo.getPassword())){
                //获取权限code集合
                List<String> listCode=userMapper.getUserPermCode(userInfo.getId());
                if(listCode!=null){
                    userInfo.setPermCodeList(listCode);
                }
                userInfo.setPermCodeList(listCode);
                return userInfo;
            } else {
                throw new LoginInfoException(userName);
            }
        } else {
            throw new LoginInfoException(userName);
        }

    }
    /**
     * 获取加密后的密码
     * @param userId 用户id
     * @return
     */
    public User getUserById(String userId) {
        User user=userMapper.getUserById(userId);
        //获取权限code集合
        List<String>listCode=userMapper.getUserPermCode(userId);
        if(listCode!=null){
            user.setPermCodeList(listCode);
        }
        return user;
    }

    public String getRole(String userId){
        List<String> roles=userMapper.getRole(userId);
        String roleL="";
        for(String role:roles){
            roleL=roleL+role+",";
        }
        if(!roleL.equals("")){
            roleL=roleL.substring(0,roleL.length()-1);
        }
        return roleL;
    }
    //注册用户
    public String userRegister(User user) throws BusinessException {
        String registCode="";
        //验证该用户名是否已经存在
        if(!StringUtils.isEmpty(user.getUserName())){
            int num=userMapper.getUserByUserName(user.getUserName());
            if(num>0){
                throw new BusinessException(500,"该用户名已存在!");
            }else{
                registCode=passwordEncoding(user.getPassword(), user.getId());
                user.setRegistCode(registCode);//生成注册码
                user.setPassword(passwordEncoding(user.getPassword(), user.getId()));//设置用户密码
                userMapper.userRegister(user);//写入数据库
            }
        }
        return registCode;//返回注册码
    }

    // 通过id删除用户信息
    public void deleteUserById(String userId) {
        userMapper.deleteUserById(userId);
    }

    //修改用户信息
    public void userUpdate(User user) {
        if(!StringUtils.isEmpty(user.getId())){
            userMapper.userUpdate(user);
        }
    }
    //查询用户列表数据
    public PageModel userList(UserSearchParam param, int pageIndex, int pageSize,String loginUserId) {
        PageModel pm=new PageModel();
        List<User> returnList=userMapper.getUserList(param,getStartRow(pageIndex,pageSize),pageSize);
        int count=0;
        if(pageIndex==1){
            //查询总条数
            count=userMapper.getUserListCount(param);
            if(count>0){
                count=count-1;
            }
        }
        for(int i=0;i<returnList.size();i++){
            if(returnList.get(i).getId().equals(loginUserId)){
                returnList.remove(i);
            }
        }
        pm.setCount(count);
        pm.setList(returnList);
        return  pm;
    }
    //查询用户列表数据
    public PageModel userListWithMsg(UserSearchParam param, int pageIndex, int pageSize,String loginUserId) {
        PageModel pm=new PageModel();
        List<User> returnList=userMapper.getUserList(param,getStartRow(pageIndex,pageSize),pageSize);
        int count=0;
        if(pageIndex==1){
            //查询总条数
            count=userMapper.getUserListCount(param);
            if(count>0){
                count=count-1;
            }
        }
        //获取最新消息情况

        for(int i=0;i<returnList.size();i++){
            if(returnList.get(i).getId().equals(loginUserId)){
                returnList.remove(i);
            }else{
                MessageReturnParam listNotRead=messageMapper.getMessageForListByToken(getToken(returnList.get(i).getId(),loginUserId),loginUserId);
                if(listNotRead!=null){
                    Message msg= messageMapper.getLastMessage(getToken(listNotRead.getPublishUser(),loginUserId));
                    if(msg!=null){
                        listNotRead.setLastMessage(msg);
                    }
                }
                returnList.get(i).setNewMsg(listNotRead);
            }
        }
        pm.setCount(count);
        pm.setList(returnList);
        return  pm;
    }

    //根据用户名获取用户信息
   /* public String getUserIdByUserName(String username) {
        return null;
    }*/


    public void userCheckByuserId(User user) {
        boolean flag=false;
        flag=userMapper.userCheckByuserId(user.getId(),user.getCheckStatus());
        if(user.getCheckStatus().equals("1")){
            if(flag){
                String msgCount= SmsModelUtil.USER_CHECK(user.getUserName());
                String str= SmsClientSend.sendSms(sms_url,sms_ID,sms_account,sms_psw,user.getPhone(),msgCount );
                Message message =new Message();
                message.setPublishUser(user.getId());
                message.setContent(msgCount);
                message.setToken(messageService.getToken(user.getId(),user.getId()));
                message.setPublishTime(new Date());
                message.setReceiveUser(user.getId());
                messageService.addMessage(message);
            }
        }
    }

    /**
     * 查询该代理商下是否 有用户
     * @param agentId
     */
    public int getUserByAgentId(String agentId) {
        int count=userMapper.getUserByAgentId(agentId);
        return count;
    }

    //判断是否有用户
    public List<User> justPhoneAndName(String username,String phone){
        return userMapper.justPhoneAndName(username,phone);
    }
    //修改密码
    public int changePwd(String username,String phone,String password){
        String id=userMapper.justPhoneAndName(username,phone).get(0).getId();
        password=passwordEncoding(password, id);//设置用户密码
        return userMapper.changePwd(id,password);
    }

}
